package com.health.crm.sys.config;

import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.druid.DruidConfig;
import com.health.core.constant.RedisConstants;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DatabaseDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author tidudada
 * @Description 使用官方文档的方式来放入数据源
 * @Date 上午8:47 2022/1/26
 **/

@Slf4j
@Configuration
@Setter
@ConfigurationProperties(prefix = "datasource.config")
@Component
public class CrmEnterpriseConfigService {

    private String url;

    private String username;

    private String password;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static HashMap<String, DataSourceProperty> map;


    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    // 项目初始化操作
    public void initialize() {
        enterpriseDatasourceToR();
        logger.info("CRM - 初始化完成 😭😭😭😭😭😭😭");
    }

    protected void enterpriseDatasourceToR() {
        HashMap<String, String> hashMap = new HashMap<>();
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            DataSourceProperty property = map.get(key);
            String string = JSON.toJSONString(property);
            hashMap.put(key,string);
        }
        redisTemplate.opsForHash().putAll(RedisConstants.CRM_ENTERPRISE_DATASOURCE_ALL,hashMap);
    }

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return new AbstractJdbcDataSourceProvider(DatabaseDriver.MYSQL.getDriverClassName(),
                this.url, this.username, this.password) {
            @Override
            protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
                ResultSet rs = statement.executeQuery("SELECT * FROM rcrm_dbcenter WHERE type = 'rcrm'");
                HashMap<String, DataSourceProperty> map = new HashMap<>();
                while (rs.next()) {
                    // 企业号
                    String companyCode = rs.getString("companycode");
                    String url = append(rs.getString("dbhost"),rs.getString("dbport"),rs.getString("dbname"));
                    String username = rs.getString("dbuser");
                    String password = rs.getString("dbpwd");
                    DataSourceProperty property = new DataSourceProperty();
                    property.setDruid(new DruidConfig());
                    property.setUsername(username);
                    property.setPassword(password);
                    property.setUrl(url);
                    map.put(companyCode,property);
                }
                CrmEnterpriseConfigService.map = map;
                return map;
            }
            public String append(String dbHost, String dbPort, String dbName) {
                return "jdbc:mysql://" +
                        dbHost +
                        ":" +
                        dbPort +
                        "/" +
                        dbName +
                        "?" +
                        "autoReconnect=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
            }
        };
    }

}
